<template>
  <div>
    <div class="g-form form">
      <LiquidityHeader title="Add Liquidity" @back="$emit('change', 'home')" />
      <SwapField
        v-model="amountA"
        type="liquidity"
        :token="tokenA"
        @change="calcAmountB"
        @select="showSelectToken('tokenA')"
      />
      <div class="plus">
        <i class="iconfont icon-add"></i>
      </div>
      <SwapField
        v-model="amountB"
        type="liquidity"
        :token="tokenB"
        @change="calcAmountA"
        @select="showSelectToken('tokenB')"
      />
      <div class="info">
        <div class="info__title">
          <span>PRICE AND POOL SHARE</span>
        </div>
        <div class="info__list">
          <div class="item">
            <span>{{ token0Price }}</span>
            <i>{{ token0.symbol }} per {{ token1.symbol }}</i>
          </div>
          <div class="item">
            <span>{{ token1Price }}</span>
            <i>{{ token1.symbol }} per {{ token0.symbol }}</i>
          </div>
          <div class="item">
            <span v-if="userLiquidityPercent">
              {{ userLiquidityPercent }}%
            </span>
            <span v-else>--</span>
            <i>Share of Pool</i>
          </div>
        </div>
      </div>
      <ButtonBase label="Supply" @click="isShowConfirm = true" />
    </div>
    <LPTokenCard :pair="pair" />
    <NouDialog close-on-click-modal :visible.sync="isShowToken">
      <SwapToken @close="isShowToken = false" @select="hideSelectToken" />
    </NouDialog>
    <NouDialog close-on-click-modal :visible.sync="isShowConfirm">
      <LiquidityConfirm
        :pair="pair"
        :amountA="amountA"
        :amountB="amountB"
        :amountLP="amountLP"
        :percent="userLiquidityPercent"
        type="add"
        @close="isShowConfirm = false"
        @confirm="confirm"
      />
    </NouDialog>
  </div>
</template>

<script>
import SwapToken from "@/components/SwapToken";
import SwapField from "@/components/SwapField";
import ButtonBase from "@/components/common/ButtonBase";
import LPTokenCard from "@/components/LPTokenCard";
import LiquidityHeader from "./LiquidityHeader";
import NouDialog from "@/components/common/NouDialog";
import LiquidityConfirm from "@/components/LiquidityConfirm";

import { getTokenBySymbol } from "@/utils/token";
import {
  getPairInfo,
  getLiquidityQuote,
  addLiquidity,
  getBalance,
} from "@/init";
import { mapState } from "vuex";

export default {
  components: {
    SwapToken,
    SwapField,
    ButtonBase,
    NouDialog,
    LPTokenCard,
    LiquidityHeader,
    LiquidityConfirm,
  },
  data() {
    return {
      amountA: 0,
      amountB: 0,
      tokenA: getTokenBySymbol("TSE"),
      tokenB: getTokenBySymbol("BUSD"),
      pair: null,
      isShowToken: false,
      selectToken: "tokenA",
      isShowConfirm: false,
      amountLP: 0,
      timeout: null,
    };
  },
  computed: {
    token0() {
      return (this.pair && this.pair.token0) || {};
    },
    token1() {
      return (this.pair && this.pair.token1) || {};
    },
    token0Price() {
      return (this.pair && this.pair._token0Price) || {};
    },
    token1Price() {
      return (this.pair && this.pair._token1Price) || {};
    },
    totalSupply() {
      const amount = (this.pair && +this.pair.totalSupply) || 0;
      return amount + this.amountLP;
    },
    userLiquidity() {
      return (this.pair && this.pair.userLiquidity) || 0;
    },
    userLiquidityPercent() {
      if (this.amountLP && this.totalSupply) {
        return Math.ceil((this.amountLP / this.totalSupply) * 10000) / 100;
      }
    },
  },
  watch: {
    ...mapState({
      account: (state) => state.account,
    }),
    "tokenA.address"() {
      this.loadPair();
    },
    "tokenB.address"() {
      this.loadPair();
    },
    account() {
      this.loadPair();
    },
  },
  mounted() {
    this.loadPair();
  },
  methods: {
    async loadPair() {
      const pair = await getPairInfo(this.tokenA, this.tokenB);
      this.pair = pair;
      this.calcAmountB();
      this.getBalanceOf();
      this.amountA = 1;
    },
    calcAmountA() {
      clearTimeout(this.timeout);
      this.timeout = setTimeout(async () => {
        const result = await getLiquidityQuote({
          tokenA: this.tokenB,
          tokenB: this.tokenA,
          totalSupply: this.pair._totalSupply,
          amount: this.amountB,
        });
        const { amountB, amountLP } = result || {};
        console.log("result", result);
        this.amountA = +amountB;
        this.amountLP = +amountLP;
      }, 1000);
    },
    async calcAmountB() {
      clearTimeout(this.timeout);
      this.timeout = setTimeout(async () => {
        const result = await getLiquidityQuote({
          tokenA: this.tokenA,
          tokenB: this.tokenB,
          totalSupply: this.pair._totalSupply,
          amount: this.amountA,
        });
        const { amountB, amountLP } = result || {};
        console.log("result", result);
        this.amountB = +amountB;
        this.amountLP = +amountLP;
      }, 1000);
    },
    async getBalanceOf() {
      const res0 = await getBalance(this.tokenA);
      this.$set(this.tokenA, "balance", res0.balance);
      this.$set(this.tokenA, "allowance", res0.allowance);
      const res1 = await getBalance(this.tokenB);
      this.$set(this.tokenB, "balance", res1.balance);
      this.$set(this.tokenB, "allowance", res1.allowance);
    },
    hideSelectToken(token) {
      const { symbol } = token;
      if (this.selectToken === "tokenA") {
        this.tokenA = getTokenBySymbol(symbol);
      } else {
        this.tokenB = getTokenBySymbol(symbol);
      }
      this.isShowToken = false;
    },
    showSelectToken(type) {
      this.selectToken = type;
      this.isShowToken = true;
    },
    async confirm() {
      this.isShowConfirm = false;
      await addLiquidity({
        tokenA: this.tokenA,
        tokenB: this.tokenB,
        amount: this.amountA,
        slippage: 5,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.form {
  .head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 30px;
    span {
      font-size: 16px;
      line-height: 1;
      font-family: "Roboto Bold";
      color: var(--color);
    }

    .g-clickable {
      width: 28px;
      height: 28px;
      display: flex;
      align-items: center;
      justify-content: center;

      &.back {
        i {
          transform: rotate(90deg);
        }
      }
      &.help {
        border-radius: 14px;
        background-color: rgba(255, 255, 255, 0.03);
      }
      i {
        font-size: 24px;
        color: var(--color);
      }
    }
  }
  .plus {
    margin-top: 20px;
    height: 24px;
    display: flex;
    align-items: center;
    justify-content: center;

    i {
      font-size: 24px;
      font-weight: 500;
      color: var(--color);
    }
  }
  .info {
    margin: 20px 0 30px;
    &__title {
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      margin-bottom: 10px;

      span {
        font-size: 12px;
        font-family: "Roboto Bold";
        color: var(--color-content);
      }
    }

    &__list {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border: 1px solid var(--border-color);
      padding: 20px;
      border-radius: 10px;

      .item {
        display: flex;
        align-items: center;
        flex-direction: column;

        span {
          font-size: 16px;
          font-family: "Roboto Bold";
          color: var(--color);
          margin-bottom: 10px;
        }

        i {
          font-size: 14px;
          font-family: "Roboto Medium";
          color: var(--color-content);
        }
      }
    }
  }
}
</style>
